<template>
  <el-container>
    <el-scrollbar height="calc(95vh - 61px)" style="width: 100%">
      <el-header>
        <div class="header-wrapper">
          <el-form inline @submit.prevent="onSearch" :model="formData" size="small">
            <el-form-item prop="name">
              <el-input
                name="name"
                placeholder="按名称搜索"
                v-model="formData.name"
                clearable
                @clear="onSearch"
              />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" native-type="submit">搜索</el-button>
            </el-form-item>
          </el-form>
          <div class="right-side">
            <el-button type="primary" @click="onRoleAddModalVisible">
              <el-icon>
                <Plus />
              </el-icon>
              添加角色
            </el-button>
          </div>
        </div>
      </el-header>
      <el-main>
        <el-table :data="dataSource" stripe border empty-text="暂无数据" v-loading="loading">
          <el-table-column type="index" label="序号" width="70" align="center"></el-table-column>
          <el-table-column prop="name" label="名称" align="center">
            <template #default="scope">
              <el-input
                type="text"
                v-model="scope.row.name"
                maxlength="20"
                center
                placeholder="输入名称"
                @change="onRoleUpdate(scope.row)"
                :readonly="!useControllerAuth.hasAuth('role.update')"
                suffix-icon="Edit"
              />
            </template>
          </el-table-column>
          <el-table-column prop="dataType" align="center" label="权限类型">
            <template #default="scope">
              <!--            {{ useDataType(scope.row.dataType) }} -->
              <el-select
                v-model="scope.row.dataType"
                placeholder="选择"
                @change="onRoleUpdate(scope.row)"
                :disabled="!useControllerAuth.hasAuth('role.update')"
              >
                <el-option
                  v-for="item in dataTypeDataSource"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column
            prop="functions"
            label="角色权限"
            type="expand"
            width="100"
            align="center"
          >
            <template #default="scope">
              <el-tag
                class="mx-1"
                :closable="
                  scope.row.dataType !== 'ROOT' && useControllerAuth.hasAuth('role.update')
                "
                hit
                v-for="item of scope.row.functions || []"
                :key="item"
                type="success"
                @close="onTagClose(scope.row, item)"
              >
                {{ roleFunc[item] }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="updateTime" label="最后修改时间" align="center" />
          <el-table-column label="操作" align="center">
            <template #default="scope">
              <el-button-group>
                <el-space
                  v-if="scope.row.dataType !== 'ROOT' && useControllerAuth.hasAuth('role.update')"
                >
                  <el-button size="small" @click="onRoleEdit(scope.row)">权限编辑</el-button>
                </el-space>
                <el-space v-if="useControllerAuth.hasAuth('role.remove')">
                  <el-popconfirm
                    title="确定要删除吗？"
                    width="200"
                    @confirm="onRemoveRole(scope.row)"
                    confirm-button-text="确定"
                    cancel-button-text="取消"
                    icon="InfoFilled"
                    icon-color="#626AEF"
                  >
                    <template #reference>
                      <el-button size="small" type="danger">删除角色</el-button>
                    </template>
                  </el-popconfirm>
                </el-space>
              </el-button-group>
            </template>
          </el-table-column>
        </el-table>
      </el-main>
      <el-footer>
        <el-pagination
          layout="prev, pager, next"
          :total="formData.total"
          :page-size="formData.size"
          v-if="formData.total > formData.size"
          @current-change="onCurrentChange"
        />
      </el-footer>
    </el-scrollbar>
  </el-container>

  <el-dialog
    v-model="roleModalVisible"
    :title="`权限编辑 [${userInfo.name}]`"
    width="66
  0"
    @close="onRefresh"
    style="width: 660px"
  >
    <RoleComponent :user-info="userInfo" @close="onRoleClose" />
  </el-dialog>
  <el-dialog v-model="roleAddModalVisible" title="添加角色" width="500">
    <RoleAddComponent :data-type-list="dataTypeDataSource" @close="onRoleAddModalHidden" />
  </el-dialog>
</template>

<script lang="ts" setup>
import type { RoleType, Search } from "@vs/Role/RoleType";
import { fetchRoleFunction, fetchRoleSearch, fetchRoleUpdate, fetchRoleRemove } from "@/http/role";
import { onBeforeMount, reactive, ref } from "vue";
import type { RoleFunctions } from "@/libs/useEnum";
import { useFunctions } from "@/libs/useEnum";
import { ElMessageBox } from "element-plus";
import RoleComponent from "@cs/Role/Role-Component.vue";
import RoleAddComponent from "@vs/Role/Role-Add-Component.vue";
import { useController } from "@/libs/useUserInfo";

const dataSource = ref<RoleType[]>([]);
const loading = ref<boolean>(false);
const roleFunc = ref<any>({});

const dataTypeDataSource = ref([
  {
    label: "管理员",
    value: "ROOT"
  },
  {
    label: "超级用户",
    value: "ALL_DATA"
  },
  {
    label: "普通用户",
    value: "ME_DATA"
  }
]);

const userInfo = ref<RoleType | {}>({});
const roleModalVisible = ref<boolean>(false);
const roleAddModalVisible = ref<boolean>(false);
const useControllerAuth = useController();
const formData = reactive<Search>({
  name: "",
  isAsc: false,
  currentPage: 1,
  total: 0,
  size: 15
});

const fetchDataSource = async function (): Promise<RoleType[]> {
  loading.value = true;
  const res = await fetchRoleSearch(formData).finally(() => (loading.value = false));
  formData.total = res.total;
  return Promise.resolve(res?.records || []);
};
const setDataSource = function (list: RoleType[]) {
  dataSource.value = list;
};
const onSearch = function () {
  formData.currentPage = 1;
  onRefresh();
};
const fetchFunction = function () {
  fetchRoleFunction().then((res: RoleFunctions[]) => {
    roleFunc.value = useFunctions(res);
  });
};
const onRoleEdit = function (event: RoleType) {
  roleModalVisible.value = true;
  userInfo.value = event;
};
const onRoleClose = function (event: any) {
  roleModalVisible.value = false;
  event && onRefresh();
};
const onRemoveRole = function (event: RoleType) {
  fetchRoleRemove(event).then(onRefresh);
};
const init = async function () {
  return await fetchDataSource();
};

const onCurrentChange = function (n: number) {
  formData.currentPage = n;
  onRefresh();
};

const onTagClose = function (event: any, role: string) {
  ElMessageBox.confirm("此操作将会修改此角色的权限，确定继续吗？", "提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning"
  }).then(() => {
    event.functions = event.functions.filter((it: string) => {
      return it !== role;
    });
    fetchRoleUpdate(event);
  });
};
const onRoleUpdate = function (event: RoleType) {
  fetchRoleUpdate(event).catch(onRefresh);
};
const onRefresh = async function () {
  const list = await init();
  setDataSource(list);
};

const onRoleAddModalVisible = function () {
  roleAddModalVisible.value = true;
};
const onRoleAddModalHidden = function (event?: boolean) {
  roleAddModalVisible.value = false;
  event && onRefresh();
};
onBeforeMount(async () => {
  await onRefresh();
  fetchFunction();
});
</script>

<style scoped>
.header-wrapper {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>
